<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCurrentInstance } from "vue";
import axios from "axios";
import { getUserInfo } from "@/utils/auth";

// 获取当前实例以访问全局属性
// const instance = getCurrentInstance();
// const $http = instance?.appContext.config.globalProperties.$http; // 已通过import直接使用axios

// 搜索表单
const searchForm = ref({
  clueId: "",
  phone: "",
  status: "",
  channel: "",
  assignName: "",
});

// 线索列表数据
const clueList = ref([]);

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 从用户信息中获取角色
const getUserRole = () => {
  const userInfo = getUserInfo();
  // 添加调试信息
  console.log('线索页面用户信息:', userInfo);
  // 确保返回正确的角色，严格区分不同角色类型
  if (userInfo && userInfo.role) {
    console.log('线索页面获取到的角色:', userInfo.role);
    return userInfo.role;
  }
  // 默认返回空字符串，避免未登录时显示操作按钮
  console.log('线索页面未获取到角色信息，返回空');
  return '';
};

// 角色标识 - 从用户信息中获取真实角色
const roleLabel = ref(getUserRole());

// 计算属性：根据角色决定按钮显示
// admin角色只显示分配按钮
const showAssignButton = computed(() => roleLabel.value === "admin");
// 线索操作员角色显示其他操作按钮
const showOperatorButtons = computed(() => roleLabel.value === "clue_operator");

// 状态选项
const statusOptions = [
  { label: "全部", value: "" },
  { label: "待分配", value: "1" },
  { label: "待跟进", value: "2" },
  { label: "跟进中", value: "3" },
  { label: "伪线索", value: "4" },
  { label: "转为商机", value: "5" }
];

// 渠道来源选项
const channelOptions = [
  { label: "全部", value: "" },
  { label: "推广介绍", value: "1" },
  { label: "线上活动", value: "2" },
];

// 获取线索列表
const getClueList = async () => {
  try {
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      clueId: searchForm.value.clueId,
      phone: searchForm.value.phone,
      status: searchForm.value.status,
      channel: searchForm.value.channel,
      assignName: searchForm.value.assignName,
    };

    const response = await axios.get("/api/clues", { params });

    if (response.data && response.data.code === 1) {
      clueList.value = response.data.data.rows || [];
      pagination.value.total = response.data.data.total || 0;
    } else {
      ElMessage.error(response.data?.msg || "获取线索列表失败");
    }
  } catch (error) {
    console.error("获取线索列表错误:", error);
    ElMessage.error("获取线索列表失败");
  }
};



// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
  getClueList();
};

// 重置
const handleReset = () => {
  searchForm.value = {
    clueId: "",
    phone: "",
    status: "",
    channel: "",
    assignName: "",
  };
  pagination.value.currentPage = 1;
  getClueList();
};

// 页码变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  getClueList();
};

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  getClueList();
};

// 分配线索
const handleAssign = async (row) => {
  try {
    // 模拟选择用户 - 实际应该弹出用户选择对话框
    const userId = 13;
    const response = await axios.put(`/api/clues/assign/${row.id}/${userId}`);

    if (response.data && response.data.code === 1) {
      ElMessage.success("分配成功");
      getClueList();
    } else {
      ElMessage.error(response.data?.msg || "分配失败");
    }
  } catch (error) {
    console.error("分配线索错误:", error);
    ElMessage.error("分配失败");
  }
};

// 跟进线索相关响应式数据
const followClueDialogVisible = ref(false);
const followClueForm = ref({
  id: '',
  phone: '',
  channel: '',
  activityId: '',
  name: '',
  gender: '',
  age: '',
  wechat: '',
  qq: '',
  userId: '',
  status: '',
  subject: '',
  level: '',
  nextTime: '',
  record: ''
});
const followClueFormRules = {
  subject: [
    { required: true, message: '请选择意向学科', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择意向等级', trigger: 'change' }
  ],
  nextTime: [
    { required: true, message: '请选择下次跟进时间', trigger: 'change' }
  ],
  record: [
    { required: true, message: '请输入跟进记录', trigger: 'blur' },
    { min: 1, max: 200, message: '跟进记录长度在 1 到 200 个字符', trigger: 'blur' }
  ]
};
const followClueFormRef = ref(null);
const trackRecords = ref([]);
const loading = ref(false);

// 意向学科选项
const subjectOptions = [
  { label: '人工智能(AI)', value: 1 },
  { label: '大数据', value: 2 },
  { label: '鸿蒙开发', value: 3 },
  { label: '嵌入式开发', value: 4 },
  { label: 'Java开发', value: 5 },
  { label: '测试开发', value: 6 }
];

// 意向等级选项
const levelOptions = [
  { label: '高', value: 1 },
  { label: '中', value: 2 },
  { label: '低', value: 3 },
  { label: '不确定', value: 4 }
];

// 根据ID查询线索详情
const getClueDetail = async (id) => {
  try {
    loading.value = true;
    const response = await axios.get(`/api/clues/${id}`);
    
    if (response.data && response.data.code === 1 && response.data.data) {
      const data = response.data.data;
      // 填充表单数据
      followClueForm.value = {
        id: data.id,
        phone: data.phone,
        channel: data.channel,
        activityId: data.activityId,
        name: data.name,
        gender: data.gender,
        age: data.age,
        wechat: data.wechat,
        qq: data.qq,
        userId: data.userId,
        status: data.status,
        subject: data.subject,
        level: data.level,
        nextTime: data.nextTime,
        record: '' // 跟进记录需要用户输入
      };
      // 填充历史跟踪记录
      trackRecords.value = data.trackRecords || [];
    } else {
      ElMessage.error(response.data?.msg || '获取线索详情失败');
    }
  } catch (error) {
    console.error('获取线索详情错误:', error);
    ElMessage.error('获取线索详情失败');
  } finally {
    loading.value = false;
  }
};

// 打开跟进线索对话框
const handleFollow = async (row) => {
  await getClueDetail(row.id);
  followClueDialogVisible.value = true;
};

// 关闭跟进线索对话框
const closeFollowClueDialog = () => {
  followClueDialogVisible.value = false;
  followClueFormRef.value?.resetFields();
  trackRecords.value = [];
};

// 提交跟进线索表单
const submitFollowClue = async () => {
  try {
    // 验证表单
    await followClueFormRef.value.validate();
    
    // 准备提交数据
    const submitData = { ...followClueForm.value };
    // 将空字符串转换为null或删除
    Object.keys(submitData).forEach(key => {
      if (submitData[key] === '') {
        submitData[key] = null;
      }
    });
    
    // 调用接口
    const response = await axios.put('/api/clues', submitData);
    
    if (response.data && response.data.code === 1) {
      ElMessage.success('跟进线索成功');
      closeFollowClueDialog();
      getClueList(); // 重新获取线索列表
    } else {
      ElMessage.error(response.data?.msg || '跟进线索失败');
    }
  } catch (error) {
    if (error === false) {
      // 表单验证失败，不做处理
      return;
    }
    console.error('跟进线索错误:', error);
    ElMessage.error('跟进线索失败');
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  return dateTime;
};

// 格式化意向学科
const formatSubject = (subject) => {
  const subjectMap = subjectOptions.find(option => option.value === subject);
  return subjectMap ? subjectMap.label : subject;
};

// 格式化意向等级
const formatLevel = (level) => {
  const levelMap = levelOptions.find(option => option.value === level);
  return levelMap ? levelMap.label : level;
};

// 伪线索处理相关响应式数据
const falseClueDialogVisible = ref(false);
const falseClueForm = ref({
  reason: 1, // 默认选择第一个原因
  remark: ''
});
const falseClueFormRules = {
  reason: [
    { required: true, message: '请选择标记原因', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入备注说明', trigger: 'blur' },
    { min: 2, max: 200, message: '备注说明长度在 2 到 200 个字符', trigger: 'blur' }
  ]
};
const falseClueFormRef = ref(null);
const currentClueId = ref(null);

// 伪线索原因选项
const falseReasonOptions = [
  { label: '空号', value: 1 },
  { label: '停机', value: 2 },
  { label: '竞品', value: 3 },
  { label: '无法联系', value: 4 },
  { label: '其他', value: 5 }
];

// 打开伪线索处理对话框
const openFalseClueDialog = (row) => {
  currentClueId.value = row.id;
  falseClueForm.value = {
    reason: 1,
    remark: ''
  };
  falseClueDialogVisible.value = true;
};

// 关闭伪线索处理对话框
const closeFalseClueDialog = () => {
  falseClueDialogVisible.value = false;
  falseClueFormRef.value?.resetFields();
  currentClueId.value = null;
};

// 提交伪线索处理表单
const submitFalseClue = async () => {
  try {
    // 验证表单
    await falseClueFormRef.value.validate();
    
    // 准备提交数据
    const params = { ...falseClueForm.value };
    if (!params.remark) {
      params.remark = null;
    }
    
    // 调用接口
    const response = await axios.put(`/api/clues/false/${currentClueId.value}`, params);
    
    if (response.data && response.data.code === 1) {
      ElMessage.success("操作成功");
      closeFalseClueDialog();
      getClueList(); // 重新获取线索列表
    } else {
      ElMessage.error(response.data?.msg || "操作失败");
    }
  } catch (error) {
    if (error === false) {
      // 表单验证失败，不做处理
      return;
    }
    console.error("伪线索处理错误:", error);
    ElMessage.error("操作失败");
  }
};

// 伪线索处理
const handleFalseClue = (row) => {
  openFalseClueDialog(row);
};

// 转商机
const handleToBusiness = async (row) => {
  try {
    await ElMessageBox.confirm("确定将此线索转为商机吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await axios.put(`/api/clues/toBusiness/${row.id}`);

    if (response.data && response.data.code === 1) {
      ElMessage.success("转商机成功");
      getClueList();
    } else {
      ElMessage.error(response.data?.msg || "转商机失败");
    }
  } catch (error) {
    if (error === "cancel") return;
    console.error("转商机错误:", error);
    ElMessage.error("转商机失败");
  }
};

// 新建线索相关响应式数据
const addClueDialogVisible = ref(false);
const addClueForm = ref({
  phone: '',
  channel: '',
  activityId: '',
  name: '',
  gender: '',
  age: '',
  wechat: '',
  qq: ''
});
const addClueFormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  channel: [
    { required: true, message: '请选择渠道来源', trigger: 'change' }
  ]
};
const addClueFormRef = ref(null);

// 活动列表数据
const activityOptions = ref([]);
const activityLoading = ref(false);

// 获取活动列表
const getActivityList = async (channelType) => {
  if (!channelType) {
    activityOptions.value = [];
    addClueForm.value.activityId = '';
    return;
  }
  
  try {
    activityLoading.value = true;
    const response = await axios.get(`/api/activities/type/${channelType}`);
    
    if (response.data && response.data.code === 1 && response.data.data) {
      activityOptions.value = response.data.data.map(activity => ({
        label: activity.name,
        value: activity.id
      }));
    } else {
      activityOptions.value = [];
    }
    
    // 重置活动选择
    addClueForm.value.activityId = '';
  } catch (error) {
    console.error('获取活动列表错误:', error);
    activityOptions.value = [];
  } finally {
    activityLoading.value = false;
  }
};

// 监听渠道变化
const handleChannelChange = () => {
  getActivityList(addClueForm.value.channel);
};

// 打开添加线索对话框
const handleAddClue = () => {
  // 重置表单
  addClueForm.value = {
    phone: '',
    channel: '',
    activityId: '',
    name: '',
    gender: '',
    age: '',
    wechat: '',
    qq: ''
  };
  // 重置活动列表
  activityOptions.value = [];
  addClueDialogVisible.value = true;
};

// 提交添加线索表单
const submitAddClue = async () => {
  try {
    // 验证表单
    await addClueFormRef.value.validate();
    
    // 准备提交数据
    const submitData = { ...addClueForm.value };
    // 将空字符串转换为null或删除
    Object.keys(submitData).forEach(key => {
      if (submitData[key] === '') {
        submitData[key] = null;
      }
    });
    
    // 调用接口
    const response = await axios.post('/api/clues', submitData);
    
    if (response.data && response.data.code === 1) {
      ElMessage.success('添加线索成功');
      closeAddClueDialog();
      getClueList(); // 重新获取线索列表
    } else {
      ElMessage.error(response.data?.msg || '添加线索失败');
    }
  } catch (error) {
    if (error === false) {
      // 表单验证失败，不做处理
      return;
    }
    console.error('添加线索错误:', error);
    ElMessage.error('添加线索失败');
  }
};

// 关闭添加线索对话框
const closeAddClueDialog = () => {
  addClueDialogVisible.value = false;
  addClueFormRef.value?.resetFields();
  // 清空活动列表
  activityOptions.value = [];
};

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    1: "待分配",
    2: "待跟进",
    3: "跟进中",
    4: "伪线索",
    5: "转为商机"
  };
  return statusMap[status] || "未知";
};

// 格式化渠道来源
const formatChannel = (channel) => {
  const channelMap = {
    1: "推广介绍",
    2: "线上活动",
  };
  return channelMap[channel] || "未知";
};

// 组件挂载时获取数据
onMounted(() => {
  // 重新获取用户角色信息，确保权限控制准确
  roleLabel.value = getUserRole();
  getClueList();
});
</script>

<template>
  <div class="clue-management">
    <!-- 主要内容区域 - 添加水平和垂直滚动容器 -->
    <div class="main-content-wrapper">
      <el-card>
        <!-- 搜索区域 -->
        <el-form :model="searchForm" class="search-form" label-width="80px">
          <el-row :gutter="20" align="middle">
            <el-col :span="6">
              <el-form-item label="线索ID" inline>
                <el-input
                  v-model="searchForm.clueId"
                  placeholder="请输入"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="手机号" inline>
                <el-input
                  v-model="searchForm.phone"
                  placeholder="请输入"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="线索状态" inline>
                <el-select
                  v-model="searchForm.status"
                  placeholder="请选择"
                  style="width: 180px"
                >
                  <el-option
                    v-for="option in statusOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="线索来源" inline>
                <el-select
                  v-model="searchForm.channel"
                  placeholder="请选择"
                  style="width: 180px"
                >
                  <el-option
                    v-for="option in channelOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="线索归属" inline>
                <el-input
                  v-model="searchForm.assignName"
                  placeholder="请输入归属人姓名"
                  style="width: 180px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleSearch"
                  style="margin-right: 10px"
                  >搜索</el-button
                >
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 操作按钮 - 置于左边 -->
        <div class="action-buttons-left" style="margin-bottom: 20px">
          <el-button type="primary" @click="handleAddClue"
            >+ 新建线索</el-button
          >
        </div>

        <!-- 表格数据 -->
        <el-table v-loading="false" :data="clueList" style="width: 100%" border>
          <el-table-column
            prop="id"
            label="线索ID"
            width="100"
            align="center"
          />
          <el-table-column
            prop="phone"
            label="手机号"
            width="150"
            align="center"
          />
          <el-table-column
            prop="name"
            label="客户姓名"
            width="120"
            align="center"
          />
          <el-table-column label="渠道来源" width="120" align="center">
            <template #default="scope">
              {{ formatChannel(scope.row.channel) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            align="center"
          />
          <el-table-column
            prop="assignName"
            label="归属人"
            width="120"
            align="center"
          >
            <template #default="scope">
              {{ scope.row.assignName || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="线索状态" width="120" align="center">
            <template #default="scope">
              {{ formatStatus(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="nextTime"
            label="下次跟进时间"
            width="200"
            align="center"
          >
            <template #default="scope">
              {{ scope.row.nextTime || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <!-- 移除权限控制，显示所有操作按钮 -->
              <el-button
                type="primary"
                size="small"
                @click="handleAssign(scope.row)"
                style="margin-right: 10px"
              >
                分配
              </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleFollow(scope.row)"
                  style="color: #67c23a; margin-right: 10px"
                >
                  跟进
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleFalseClue(scope.row)"
                  style="color: #67c23a; margin-right: 10px"
                >
                  伪线索
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="handleToBusiness(scope.row)"
                  style="color: #67c23a"
                >
                  转商机
                </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="pagination.total"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 添加线索对话框 -->
    <el-dialog
      v-model="addClueDialogVisible"
      title="添加线索"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="addClueFormRef"
        :model="addClueForm"
        :rules="addClueFormRules"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addClueForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="addClueForm.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="渠道来源" prop="channel">
          <el-select v-model="addClueForm.channel" placeholder="请选择渠道来源" @change="handleChannelChange">
            <el-option v-for="option in channelOptions.filter(o => o.value)" :key="option.value" :label="option.label" :value="Number(option.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动信息">
          <el-select v-model="addClueForm.activityId" placeholder="请选择活动（选填）" :loading="activityLoading" filterable>
            <el-option v-for="option in activityOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addClueForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model.number="addClueForm.age" placeholder="请输入年龄（选填）" type="number" min="0" max="150" />
        </el-form-item>
        <el-form-item label="微信">
          <el-input v-model="addClueForm.wechat" placeholder="请输入微信（选填）" />
        </el-form-item>
        <el-form-item label="QQ">
          <el-input v-model="addClueForm.qq" placeholder="请输入QQ（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddClueDialog">取消</el-button>
        <el-button type="primary" @click="submitAddClue">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 伪线索处理对话框 -->
    <el-dialog
      v-model="falseClueDialogVisible"
      title="标记为伪线索"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="falseClueFormRef"
        :model="falseClueForm"
        :rules="falseClueFormRules"
        label-width="80px"
        style="margin-top: 20px"
      >
        <el-form-item label="标记原因" prop="reason">
          <el-select v-model="falseClueForm.reason" placeholder="请选择标记原因">
            <el-option v-for="option in falseReasonOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input 
            v-model="falseClueForm.remark" 
            type="textarea" 
            placeholder="请输入备注说明（必填）" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeFalseClueDialog">取消</el-button>
        <el-button type="primary" @click="submitFalseClue">确定标记</el-button>
      </template>
    </el-dialog>
    
    <!-- 跟进线索对话框 -->
    <el-dialog
      v-model="followClueDialogVisible"
      :title="`跟进线索(线索ID:${followClueForm.id})`"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="followClueFormRef"
        :model="followClueForm"
        :rules="followClueFormRules"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="followClueForm.phone" disabled placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="客户姓名">
              <el-input v-model="followClueForm.name" disabled placeholder="请输入客户姓名" />
            </el-form-item>
            <el-form-item label="渠道来源">
              <el-select v-model="followClueForm.channel" disabled placeholder="请选择渠道来源">
                <el-option v-for="option in channelOptions.filter(o => o.value)" :key="option.value" :label="option.label" :value="Number(option.value)" />
              </el-select>
            </el-form-item>
            <el-form-item label="活动信息">
              <el-select v-model="followClueForm.activityId" disabled placeholder="请选择活动">
                <el-option v-for="option in activityOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="followClueForm.gender" disabled>
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input v-model.number="followClueForm.age" disabled placeholder="请输入年龄" type="number" min="0" max="150" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="followClueForm.wechat" disabled placeholder="请输入微信" />
            </el-form-item>
            <el-form-item label="QQ">
              <el-input v-model="followClueForm.qq" disabled placeholder="请输入QQ" />
            </el-form-item>
            <el-form-item label="意向学科" prop="subject">
              <el-select v-model="followClueForm.subject" placeholder="请选择意向学科">
                <el-option v-for="option in subjectOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="意向等级" prop="level">
              <el-select v-model="followClueForm.level" placeholder="请选择意向等级">
                <el-option v-for="option in levelOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="下次跟进" prop="nextTime">
              <el-date-picker
                v-model="followClueForm.nextTime"
                type="datetime"
                placeholder="请选择下次跟进时间"
                style="width: 100%"
                value-format="YYYY-MM-DD[T]HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="跟进记录" prop="record">
          <el-input 
            v-model="followClueForm.record" 
            type="textarea" 
            placeholder="请输入跟进记录" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <!-- 跟进历史 -->
      <div style="margin-top: 30px;">
        <h3 style="margin-bottom: 15px;">跟进历史</h3>
        <el-table v-loading="loading" :data="trackRecords" style="width: 100%" border size="small">
          <el-table-column label="意向等级" width="150" align="center">
            <template #default="scope">
              {{ formatLevel(scope.row.level) }}
            </template>
          </el-table-column>
          <el-table-column label="意向学科" width="200" align="center">
            <template #default="scope">
              {{ formatSubject(scope.row.subject) }}
            </template>
          </el-table-column>
          <el-table-column prop="assignName" label="跟进人" width="100" align="center" />
          <el-table-column prop="createTime" label="跟进时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="nextTime" label="下次跟进时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.nextTime) || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="record" label="跟进记录" align="center">
            <template #default="scope">
              {{ scope.row.record || '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="closeFollowClueDialog">取消</el-button>
        <el-button type="primary" @click="submitFollowClue">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.clue-management {
  padding: 0;
}

.search-form {
  margin-bottom: 15px;
}

.action-buttons-left {
  text-align: left;
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 主内容滚动容器 */
.main-content-wrapper {
  overflow-x: auto;
  overflow-y: auto;
  max-height: calc(100vh - 100px);
  position: relative;
  min-height: 600px;
  padding: 0 15px;
  white-space: nowrap;
}

/* 确保卡片内容可以水平滚动 */
.main-content-wrapper > .el-card {
  min-width: 1320px;
  width: 100%;
}

/* 表格样式优化 */
:deep(.el-table__row) {
  height: 45px;
}

/* 调整列间距 */
:deep(.el-table__cell) {
  padding: 12px 15px;
  font-size: 14px;
  min-width: fit-content;
}
</style>
